package com.miniapp.talk.activity.family

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.annotation.NonNull
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.View
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.ArmsUtils
import com.miniapp.talk.R
import com.miniapp.talk.activity.dashen.DaShenExclusiveActivity
import com.miniapp.talk.activity.game.applyskill.ApplyGameSkillActivity
import com.miniapp.talk.activity.task.TaskCenterActivity
import com.miniapp.talk.adapter.FamilyListAdapter
import com.miniapp.talk.adapter.OrderListGodAdapter
import com.miniapp.talk.app.utils.RxUtils
import com.miniapp.talk.base.BaseWebActivity
import com.miniapp.talk.base.MyBaseArmActivity
import com.miniapp.talk.bean.*
import com.miniapp.talk.di.CommonModule
import com.miniapp.talk.di.DaggerCommonComponent
import com.miniapp.talk.service.CommonModel
import com.miniapp.talk.utils.Constant
import com.miniapp.talk.utils.DealRefreshHelper
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.android.synthetic.main.activity_family_list.*
import kotlinx.android.synthetic.main.fragment_order.*
import kotlinx.android.synthetic.main.fragment_order.ly_view_no_data
import kotlinx.android.synthetic.main.fragment_order.refresh_layout
import kotlinx.android.synthetic.main.include_title.*
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.ArrayList
import javax.inject.Inject

class FamilyListActivity : MyBaseArmActivity(), FamilyListAdapter.OnButtonClickListener {

    @Inject
    open lateinit var commonModel: CommonModel

    internal var mPullRefreshBean = PullRefreshBean()

    var mDataList = ArrayList<FamilyItem>()

    var mAdapter: FamilyListAdapter? = null

    var mIntroUrl:String? = ""

    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerCommonComponent.builder()
                .appComponent(appComponent)
                .commonModule(CommonModule())
                .build()
                .inject(this)
    }

    override fun initView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_family_list
    }

    override fun initData(savedInstanceState: Bundle?) {

        setTitle("家族")

        toolbar_right.visibility = View.VISIBLE

        img_bar_right.setImageResource(R.mipmap.cp_help)

        img_bar_right.setOnClickListener {

            if(!TextUtils.isEmpty(mIntroUrl)){
                val intent = Intent(this@FamilyListActivity, BaseWebActivity::class.java)
                intent.putExtra("url",mIntroUrl)
                intent.putExtra("title","家族介绍")
                startActivity(intent)
            }
//            ArmsUtils.startActivity(FamilyIntroActivity::class.java)
        }

        var is_family_show = intent.getIntExtra("is_family_show", 0)

        var isGod = intent.getStringExtra("is_god")

        if (is_family_show == 1) {
            tv_create.visibility = View.VISIBLE
        } else {
            tv_create.visibility = View.GONE
        }

        tv_create.setOnClickListener {
            if (isGod.equals("0")) {//不是大神
                toast("成为大神之后才可以创建家族；")
                return@setOnClickListener
            } else {
                ArmsUtils.startActivity(CreateFamilyFirstActivity::class.java)  //创建家族
            }
        }
        initRecyclerView()

        initRefreshLayout()

        getDataFromServer()

        getIntro()
    }


    private fun initRefreshLayout() {

        refresh_layout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(@NonNull refreshLayout: RefreshLayout) {


                mPullRefreshBean.setLoardMore(mPullRefreshBean, refresh_layout)

                getDataFromServer()

            }

            override fun onRefresh(@NonNull refreshLayout: RefreshLayout) {

                mPullRefreshBean.setRefresh(mPullRefreshBean, refresh_layout)

                getDataFromServer()

            }
        })

    }

    private fun initRecyclerView() {

        val manager = LinearLayoutManager(this)

        manager.setOrientation(RecyclerView.VERTICAL)

        rlv_family.setHasFixedSize(true)

        rlv_family.setLayoutManager(manager)

        mAdapter = FamilyListAdapter(this, R.layout.item_family, mDataList)

        mAdapter!!.setOnClickListener(this)

        rlv_family.setHasFixedSize(true)

        rlv_family.setLayoutManager(manager)

//        mAdapter!!.setHasStableIds(true)//防止数据错乱

        rlv_family.adapter = mAdapter

    }

    private fun getIntro(){
        RxUtils.loading(commonModel.family_introduce())
                .subscribe(object : ErrorHandleSubscriber<IntroResult>(mErrorHandler) {
                    override fun onNext(intro: IntroResult) {

                        if(intro != null && intro.data != null){
                            mIntroUrl = intro.data.url
                        }

                    }
                })
    }

    //获取数据
    private fun getDataFromServer() {

        RxUtils.loading(commonModel.getFamilyList(mPullRefreshBean.pageIndex.toString()))
                .subscribe(object : ErrorHandleSubscriber<FamilyListResult>(mErrorHandler) {
                    override fun onNext(orderResult: FamilyListResult) {

                        if (orderResult != null && orderResult.data != null) {

                            var list: List<FamilyItem> = orderResult.data

                            DealRefreshHelper<FamilyItem>().dealDataToUI(refresh_layout, mAdapter!!, ly_view_no_data, list, mDataList, mPullRefreshBean)

                        } else {
                            DealRefreshHelper<FamilyItem>().dealDataToUI(refresh_layout, mAdapter!!, ly_view_no_data, ArrayList<FamilyItem>(), mDataList, mPullRefreshBean)
                        }
                    }

                    override fun onError(t: Throwable) {
                        super.onError(t)
                        DealRefreshHelper<FamilyItem>().dealDataToUI(refresh_layout, mAdapter!!, ly_view_no_data, ArrayList<FamilyItem>(), mDataList, mPullRefreshBean)
                    }

                })

    }

    override fun itemClick(item: FamilyItem) {
        var intent = Intent(this@FamilyListActivity, FamilyDetailsActivity::class.java)
        intent.putExtra("family_id", item.family_id)
        startActivity(intent)
    }

    override fun applyJoinClick(item: FamilyItem) {//申请加入
        actionApplyFamily(item.family_id)
    }

    //申请加入家族
    private fun actionApplyFamily(family_id:String) {
        RxUtils.loading(commonModel.actionApplyFamily(family_id), this)
                .subscribe(object : ErrorHandleSubscriber<CommentBean>(mErrorHandler) {
                    override fun onNext(commentBean: CommentBean) {
                        toast(commentBean.message)
                        if (commentBean.code == 1) {
                            mPullRefreshBean.setRefresh(mPullRefreshBean, refresh_layout)

                            getDataFromServer()
                        }
                    }
                })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveMsg(event: FirstEvent) {
        val tag = event.tag
        if (Constant.FAMILYXIUGAI == tag) {

            mPullRefreshBean.setRefresh(mPullRefreshBean, refresh_layout)

            getDataFromServer()
        }
    }

}
